<template>
  <div>
    <card>
      <a-row>
        <a-input-search v-model:value="searchKey" placeholder="请输入查询名称" style="width: 95%" @search="onSearch" />
      </a-row>
      <a-directory-tree style="margin-top: 10px" v-model:selectedKeys="selectedKeys" v-model:expandedKeys="expandedKeys"
        :tree-data="data" @select="handleClick">
      </a-directory-tree>
    </card>
  </div>
</template>
<script setup>
import difference from "lodash-es/difference";
const props = defineProps({
  treeData: {
    type: Array,
  },
});
const searchKey = ref();
const expandedKeys = ref([]);
const data = ref(props.treeData);
const selectedKeys = ref([]);
const emit = defineEmits(["handleOpen"]);
// watch(expandedKeys, () => {
//   console.log("expandedKeys", expandedKeys.value);
// });
// watch(selectedKeys, () => {
//   console.log("selectedKeys", selectedKeys.value[0]);
// });

// 节点展开与收起(只展示一个节点)
// const handleExpand = (keys, { expanded, node }) => {
//   const tempKeys = ((node.parent ? node.parent.children : treeData) || []).map(({ key }) => key);
//   if (expanded) {
//     expandedKeys.value = difference(keys, tempKeys).concat(node.key);
//   } else {
//     expandedKeys.value = keys;
//   }
// };

/**
 * 树结构查询方法
 * @param {*} tree
 * @param {*} targetName
 * @param {*} path
 */
function searchTree(tree, targetName, path = []) {
  let found = false;
  for (let node of tree) {
    path.push(node.key);
    if (node.title.includes(targetName)) {
      expandedKeys.value = [...path];
      found = true;
      break;
    }
    if (node.children && node.children.length > 0) {
      if (searchTree(node.children, targetName, path)) {
        found = true;
        break;
      }
    }
    path.pop();
  }
  return found;
}

function handleClick(keys) {
  emit("handleOpen", keys[0]);
}
function onSearch() {
  expandedKeys.value = [];
  selectedKeys.value = [];
  searchTree(data.value, searchKey.value);
  emit("handleOpen", expandedKeys.value[expandedKeys.value.length - 1]);
  selectedKeys.value.push(expandedKeys.value[expandedKeys.value.length - 1]);
}
</script>
